//
//  OAuthLoginVIew.swift
//  Swift_WeiBo
//
//  Created by dajie on 15/8/31.
//  Copyright (c) 2015年 dajie. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthLoginVIew: UIViewController {

    let client_id = "2476804650"
    let redirect_uri = "http://itheima.com"
    let App_Secret = "a7a9e5be93d6abcebf2973e65abf889b"

    @IBOutlet weak var webView: UIWebView!
    override func viewDidLoad()
    {
        super.viewDidLoad()
        loadOAuthView()
    }
    
    func loadOAuthView()
    {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)&display=mobile"
        webView!.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
        webView.delegate = self;
    }
    
    @IBAction func disMissVC(sender: UIBarButtonItem)
    {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
}

//  MARK: - UIWebViewDelegate
extension OAuthLoginVIew : UIWebViewDelegate
{
    func webViewDidStartLoad(webView: UIWebView)
    {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView)
    {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?)
    {
        print("error :\(error)")
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        if (urlString.hasPrefix("https://api.weibo.com/"))
        {
            return true
        }
        
        if !(urlString.hasPrefix(redirect_uri))
        {
            return false
        }
        
        // 检查查询字符串
        if let query = request.URL?.query {
            let codeStr = "code="
            if query.hasPrefix(codeStr)
            {
                let code = (query as NSString).substringFromIndex(codeStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
                let params = ["client_id" : client_id,
                    "client_secret" : App_Secret,
                    "grant_type" : "authorization_code",
                    "code" : code,
                    "redirect_uri" : redirect_uri]
                //  通过code换取accessToken 
                UserAccountModel.getUserAccountRequest(params, complete: { (account, error) -> () in
                    if error != nil
                    {
                        SVProgressHUD.showInfoWithStatus("授权失败，请重试...")
                    }
                    else
                    {
                        self.disMissVC(UIBarButtonItem())
                    }
                })
                print(code)
            }
            else
            {
                // 重新加载授权页面
                loadOAuthView()
            }
        }
        
        return false
    }
}